package com.dfdchem.imd.kaiwu.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.application.KWApp;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.manager.GlideManager;
import com.dfdchem.imd.kaiwu.model.FileModel;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.FileUtil;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.vansz.glideimageloader.GlideImageLoader;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import zuo.biao.library.util.CommonUtil;


@Route(path = RouterPath.PROFILE_ACTIVITY)
public class ProfileActivity extends BaseActivity implements View.OnClickListener, OnHttpResponseListener, OnRefreshListener {
    private static final String TAG = "ProfileActivity";

    private SmartRefreshLayout refreshLayout;
    private RelativeLayout profile_item_user_avatar;
    private RelativeLayout profile_item_user_id;
    private RelativeLayout profile_item_user_name;
    private RelativeLayout profile_item_user_phone;
    private RelativeLayout profile_item_user_staff_no;
    private RelativeLayout profile_item_user_gender;
    private RelativeLayout profile_item_user_company;
    private RelativeLayout profile_item_user_department;
    private RelativeLayout profile_item_user_section;

    private ImageView user_avatar;
    private TextView user_id;
    private TextView user_name;
    private TextView user_phone;
    private TextView user_staff_no;
    private TextView user_gender;
    private TextView user_company;
    private TextView user_department;
    private TextView user_section;


    private BottomSheetDialog bottom_sheet_dialog;

    private static final int request_code_get_user_info = 1;
    private static final int request_code_user_info_modify = 2;
    private final static int request_code_upload_image = 3;

    private Transferee transfer;

    private User user;
    private String lastUploadAvatar;

    /**
     * 启动这个Activity的Intent
     * @param context
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, ProfileActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        initView();
        initData();
        initEvent();

        transfer = Transferee.getDefault(ProfileActivity.this);
    }

    @Override
    public void initView() {
        Log.d(TAG, this.getClass().getSimpleName() + " initView");

        refreshLayout = findViewById(R.id.refreshLayout);
        user_avatar = findViewById(R.id.user_avatar);
        profile_item_user_avatar = findViewById(R.id.profile_item_user_avatar);
        profile_item_user_id = findViewById(R.id.profile_item_user_id);
        profile_item_user_name = findViewById(R.id.profile_item_user_name);
        profile_item_user_phone = findViewById(R.id.profile_item_user_phone);
        profile_item_user_staff_no = findViewById(R.id.profile_item_user_staff_no);
        profile_item_user_gender = findViewById(R.id.profile_item_user_gender);
        profile_item_user_company = findViewById(R.id.profile_item_user_company);
        profile_item_user_department = findViewById(R.id.profile_item_user_department);
        profile_item_user_section = findViewById(R.id.profile_item_user_section);

        user_id = findViewById(R.id.user_id);
        user_name = findViewById(R.id.user_name);
        user_phone = findViewById(R.id.user_phone);
        user_staff_no = findViewById(R.id.user_staff_no);
        user_gender = findViewById(R.id.user_gender);
        user_company = findViewById(R.id.user_company);
        user_department = findViewById(R.id.user_department);
        user_section = findViewById(R.id.user_section);
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void initData() {
        Log.d(TAG, this.getClass().getSimpleName() + " initData");

        user = DataManager.getInstance().getUser();

        String avatar_url = user.getAvatar();
        if (avatar_url != null && !avatar_url.equals("")) {
            // 适配内网地址
            if (avatar_url.startsWith("/Fe/Files/Index")) {
                avatar_url = RequestUtil.URL_BASE_API + avatar_url;
            }

            new GlideManager(this).load(user_avatar, avatar_url);

            List<String> urlList = new ArrayList<>();
            urlList.add(avatar_url);

            user_avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    transfer.apply(TransferConfig.build()
                            .setImageLoader(GlideImageLoader.with(getApplicationContext()))
                            .setSourceUrlList(urlList)
                            .create()
                    ).show();
                }
            });
        }

        user_id.setText(String.format("%d", user.getId()));
        user_name.setText(user.getUserName());
        user_phone.setText(user.getPhone());
        user_staff_no.setText(user.getEmpCardNo());
        user_gender.setText(user.getGender() == 1 ? "男" : "女");

        String gender = user.getGender() == 1 ? "男" : (user.getGender() == 2 ? "女":"未知");
        user_gender.setText(gender);

        user_company.setText(user.getCompany());
        user_department.setText(user.getDepartment());
        user_section.setText(user.getSection());
    }

    @Override
    public void initEvent() {
        Log.d(TAG, this.getClass().getSimpleName() + " initEvent");

        refreshLayout.setOnRefreshListener(this);
        profile_item_user_avatar.setOnClickListener(this);
        profile_item_user_id.setOnClickListener(this);
        profile_item_user_name.setOnClickListener(this);
        profile_item_user_phone.setOnClickListener(this);
        profile_item_user_staff_no.setOnClickListener(this);
        profile_item_user_gender.setOnClickListener(this);
        profile_item_user_company.setOnClickListener(this);
        profile_item_user_department.setOnClickListener(this);
        profile_item_user_section.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.profile_item_user_id:
            case R.id.profile_item_user_name:
            case R.id.profile_item_user_phone:
            case R.id.profile_item_user_staff_no:
            case R.id.profile_item_user_gender:
            case R.id.profile_item_user_company:
            case R.id.profile_item_user_department:
            case R.id.profile_item_user_section:
                showShortToast("暂不支持修改该选项");
                break;
            case R.id.profile_item_user_avatar:
                if (bottom_sheet_dialog == null) {
                    bottom_sheet_dialog = new BottomSheetDialog(this);
                    View view = getLayoutInflater().inflate(R.layout.sheet_dialog, null);
                    bottom_sheet_dialog.setContentView(view);
                    bottom_sheet_dialog.show();

                    Button bottom_sheet_cancel = view.findViewById(R.id.bottom_sheet_cancel);
                    bottom_sheet_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bottom_sheet_dialog.dismiss();
                        }
                    });

                    Button bottom_sheet_camera = view.findViewById(R.id.bottom_sheet_camera);
                    Button bottom_sheet_photo = view.findViewById(R.id.bottom_sheet_photo);

                    bottom_sheet_camera.setOnClickListener(this);
                    bottom_sheet_photo.setOnClickListener(this);
                }
                bottom_sheet_dialog.show();
                break;
            case R.id.bottom_sheet_camera:
                bottom_sheet_dialog.dismiss();
                selectPicFromCamera();
                break;
            case R.id.bottom_sheet_photo:
                bottom_sheet_dialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE_PHOTO);
                break;
        }
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        if (requestCode == request_code_upload_image) {
            dismissProgressDialog();
        }
        if (e != null) {
            Toast.makeText(getActivity(), "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_get_user_info:
                if (refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh(250);
                }
                Resp<User> respUser = JSON.parseResp(resultJson, User.class);
                if (respUser == null || respUser.getCode() != 200) {
                    Toast.makeText(getActivity(), respUser != null ? respUser.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                User tempUser = respUser.getData();
                if (tempUser == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }
                DataManager.getInstance().saveUser(tempUser);
                initData();
                break;
            case request_code_upload_image:
                Resp<FileModel> fileModelResp = JSON.parseResp(resultJson, FileModel.class);
                Log.d(TAG, "onHttpResponse fileModelResp:" + fileModelResp);
                if (fileModelResp != null && fileModelResp.getCode() == 200 && fileModelResp.getData() != null) {
                    String fileUrl = RequestUtil.url_file_short + "/" + fileModelResp.getData().getKey();

                    if (lastPicPath != null && FileUtil.getFileSize(lastPicPath) == fileModelResp.getData().getSize()) {
                        new GlideManager(ProfileActivity.this).load(user_avatar, lastPicPath);
                    } else {
                        new GlideManager(ProfileActivity.this).load(user_avatar, fileUrl);
                    }

                    List<String> urlList = new ArrayList<>();
                    urlList.add(lastPicPath);

                    user_avatar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            transfer.apply(TransferConfig.build()
                                    .setImageLoader(GlideImageLoader.with(getApplicationContext()))
                                    .setSourceUrlList(urlList)
                                    .create()
                            ).show();
                        }
                    });

                    User tempUser1 = new User();
                    tempUser1.setAvatar(fileUrl);

                    lastUploadAvatar = fileUrl;
                    // 修改头像信息
                    runThread(TAG + "userInfoModify", new Runnable() {
                        @Override
                        public void run() {
                            RequestUtil.user_info_modify(tempUser1 ,request_code_user_info_modify,
                                    ProfileActivity.this);
                        }
                    });
                }

                break;
            case request_code_user_info_modify:
                Resp<String> result = JSON.parseResp(resultJson, String.class);
                if (result != null && result.getCode() == 200) {
                    showShortToast(result.getMsg() == null ? "修改成功" : result.getMsg());

                    if (user != null) {
                        user.setAvatar(lastUploadAvatar);
                        DataManager.getInstance().saveUser(user);
                    }
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (bottom_sheet_dialog != null) {
            bottom_sheet_dialog.dismiss();
        }

        transfer.destroy();

        super.onDestroy();
    }

    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_PHOTO = 19;

    private File cameraFile;
    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtil.isExitsSdcard()) {
            showShortToast("SD卡不存在，不能拍照");
            return;
        }

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        File cacheDir = KWApp.getInstance().getExternalCacheDir();
        if (cacheDir != null && !cacheDir.exists()) {
            cacheDir.mkdirs();
        }

        cameraFile = new File(cacheDir.getAbsolutePath(), "photo-" + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();

        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, KWApp.getInstance().getApplicationInfo().packageName + ".fileProvider", cameraFile);
        } else {
            uri = Uri.fromFile(cameraFile);
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_CAMERA:
                    if (cameraFile != null && cameraFile.exists()) {
                        String picturePath = cameraFile.getAbsolutePath();
                        Log.d(TAG, "REQUEST_CODE_CAMERA length:" + FileUtil.getFileSize(picturePath));

                        Luban.with(ProfileActivity.this)
                                .load(new File(picturePath))
                                .ignoreBy(1000)
                                .setTargetDir(cameraFile.getParent())
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        showProgressDialog("正在处理图片...");
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        dismissProgressDialog();
                                        Log.d(TAG, "OnCompressListener onSuccess:" + FileUtil.getFileSize(file.getPath()));
                                        uploadImage(file.getAbsolutePath());
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }
                                }).launch();
                    }
                case REQUEST_CODE_PHOTO:
                    if (data != null) {
                        Uri selectedImage = data.getData();
                        if (selectedImage != null) {
                            String picturePath = getPathFromUri(selectedImage);

                            uploadImage(picturePath);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 根据图库图片uri获取图片路径
     * @param selectedImage
     */
    private String getPathFromUri(Uri selectedImage) {
        if (selectedImage == null) {
            return null;
        }
        String picturePath = null;
        Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex("_data");
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        } else {
            if (selectedImage.getPath() != null) {
                File file = new File(selectedImage.getPath());
                if (!file.exists()) {
                    Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();

                }
                picturePath = file.getAbsolutePath();
            }
        }
        return picturePath;
    }

    private String lastPicPath;
    /**
     * 上传图片到服务器
     * @param filePath
     */
    private void uploadImage(String filePath){
        showProgressDialog("正在上传，请稍后...");
        lastPicPath = filePath;
        runThread(TAG + "uploadImage", new Runnable() {
            @Override
            public void run() {
                RequestUtil.uploadFile(
                        FileUtil.getFileFullName(filePath),
                        FileUtil.getMimeType(filePath),
                        filePath,
                        request_code_upload_image,
                        ProfileActivity.this);
            }
        });
    }

    @Override
    public void onRefresh(@NotNull RefreshLayout refreshlayout) {
        // 更新本地存储的用户信息
        runThread(TAG + "getUserInfo", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getUserInfo(request_code_get_user_info, ProfileActivity.this);
            }
        });
    }
}